# Create your views here.
from django.template.loader import get_template
from django.template import RequestContext
from django.http import HttpResponse, HttpResponseRedirect
from django.core.files import File
from apps.video.models import Video
import os, json
from settings import ALLOW_IPS, ROOT
from glob import iglob

def rAllowIPS(myfunc):
    def inner_func(*args, **kw):
        R = args[0]
        if 'cVideo' == myfunc.__name__:
            # IMPORTANT: if it has upload file and R.FILES.get('file') must runs before return HttpResponse
            file = R.FILES.get('file', None)
            if file: kw['file'] = file
            else: return HttpResponse(json.write({'status': False, 'message': 'could not find a file'}))

        REMOTE_ADDR = R.META.get('REMOTE_ADDR', '')
        if REMOTE_ADDR not in ALLOW_IPS:
            return HttpResponse(json.write({'status': False, 'message': 'deny your ip: %s'%REMOTE_ADDR}))

        return myfunc(*args, **kw)
    return inner_func

def cVideoByScanUploadfiles():
    """ glob .[fF][lL\[vV] in the apps/video/video/uploadfiles and parsed into database
    """

    for f in iglob(os.path.join(ROOT, 'apps', 'video', 'video', 'uploadfiles', '*.[fF][lL][vV]')):
        file = File(open(f, 'rb'))
        video = Video(upload_filename=os.path.basename(f))
        video.save()
        video.flv_file.save('%s.flv'%video.id, file)
        file.close()
        os.remove(f)

def rVideoList(R):
    cVideoByScanUploadfiles()
    videos = Video.objects.all().order_by('-id')
    t = get_template(os.path.join('video', 'index.html'))
    html = t.render(RequestContext(R, {'videos': videos}))
    return HttpResponse(html)

@rAllowIPS
def cVideo(R, file=None):
    video = Video(upload_filename=file.name)
    video.save()
    video.flv_file.save('%s.flv'%video.id, file)
    return HttpResponse(json.write({'status': True, 'id': video.id}))

def rVideo(R, video_id):
    video = Video.objects.get(id=video_id)
    t = get_template(os.path.join('video', 'video.html'))
    html = t.render(RequestContext(R, {'HTTP_HOST': R.META.get('HTTP_HOST', ''), 'video': video}))
    return HttpResponse(html)

def rVideoByEmbed(R, video_id, type):
    if 'flv' == type:
        video = Video.objects.get(id=video_id)
        content = video.flv_file.read()
        response = HttpResponse(content)
        response['Content-Type'] = 'flv-application/octet-stream'
    else:
        html = """<?xml version="1.0"?>
<videos>
    <video url="http://%s/%s/flv/%s.flv">flv file</video>
</videos>""" % (R.META.get('HTTP_HOST', ''), video_id, video_id)
        response = HttpResponse(html)
        response['Content-Type'] = 'text/xml'
    return response
